#!/usr/bin/python
# encoding=utf-8

'''
    Author:        root
    Description:    监控项目 udp 端口报警
    Create Date:    2014-04-03
'''
import socket
import simplejson
import time
import uuid
from datetime import datetime
from wm.lib import monitorlib
from wm.lib.loglib import log_info,log_error
from wm.etc.config import SOCKET
from wm.db.TransactionManager import TransactionManager

def udp_connect_check(host,port,count=SOCKET['COUNT']):
    '''
    @Udp 连接检测 | hostSocket 已经存在同类函数
    '''
    spix = host.find(':')        
    if spix != -1:
        port = host[spix:]
        host = host[0:spix]
    for i in xrange(count):
        sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)          
        try:
            start = datetime.now()
            add = (host, int(port))
            sock.sendto('PORT_IS_ALIVE',add)
            end = datetime.now()
        except Exception as e:
            log_info("udp连接失败:"+str(e))
            time.sleep(SOCKET['INTERVAL'])
            continue
        responsetime = (end - start).microseconds / 1000000.0
        return True,simplejson.dumps({"responsetime":responsetime})
    return False,simplejson.dumps({"responsetime":0})
    
def udp_check_alarm(url, udpport,row):
    '''
        UDP 端口检测结果存入数据库
    '''

    try:
        sql = None
        ret = udp_connect_check(url,int(udpport))
        tran = TransactionManager()
        try:
            tran.startTransaction()
            if ret[0] == False:
                alarmcontent = 'UDP port:'+str(udpport)
                alarmid = uuid.uuid1().__str__().replace("-","") 
                sql = "insert into alarmevent("+\
                             "id,createDate,modifyDate,alertCategory,alertContent,occurrenceDate,"+\
                                    "status,websiteName,websiteConfigInfo_id) "+\
                                    "values('" + alarmid + "'," + " CURRENT_TIMESTAMP()," + " CURRENT_TIMESTAMP()," +\
                                    "4" + ",'" + alarmcontent + "'," + "CURRENT_TIMESTAMP()," + str(0) + ",'" + row[2] + "'," +\
                                    "'" + row[0] + "')"
                            
                tran.execute(sql)
                monitorlib.update_recent_alarmevent(tran,row[0],row[2],'4',alarmcontent)
                
                sql = "insert into portavailablity("+\
                                 "id,createDate,modifyDate,port,portStatus,portType,alarmEvent_id,websiteConfigInfo_id) "+\
                                 "values(replace(uuid(),'-','')," + "CURRENT_TIMESTAMP(),CURRENT_TIMESTAMP()" +\
                                 ",'" + str(udpport) + "','" + str(0) + "',"+"1" + ",'" + str(alarmid) + "','" + row[0] + "')"        
            else:
                sql = "insert into portavailablity("+\
                                 "id,createDate,modifyDate,port,portStatus,portType,websiteConfigInfo_id) "+\
                                 "values(replace(uuid(),'-','')," + "CURRENT_TIMESTAMP(),CURRENT_TIMESTAMP()" +\
                                 ",'" + str(udpport) + "','" + str(1) + "'," + "0" +",'" + row[0] + "')"
            tran.execute(sql)
            tran.commitTransaction()
        except:
            tran.rollbackTransaction()
        finally:
            tran.close()
                                     
    except Exception as e:
        log_error("udp_check_alarm():"+str(e))
        print "udp_check_alarm():",str(e)   
    
if __name__ == '__main__':
    pass
    

